/**
 * 详细测试工具调用问题
 */

const http = require('http');

// 测试工具调用 - 使用流式接口
function testToolCallStream() {
  return new Promise((resolve, reject) => {
    console.log('🔧 测试工具调用 - 流式接口...');
    
    const postData = JSON.stringify({
      messages: [{ role: 'user', content: '查询所有任务' }],
      userId: '00287cfd-f5e2-403e-b78f-b9c327769986'
    });

    const options = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/chat-langchain/stream',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const req = http.request(options, (res) => {
      console.log(`📡 响应状态: ${res.statusCode}`);
      console.log(`📋 响应头:`, res.headers);
      
      let data = '';
      let chunkCount = 0;
      
      res.on('data', (chunk) => {
        chunkCount++;
        const chunkStr = chunk.toString();
        console.log(`📦 第${chunkCount}个chunk:`, chunkStr);
        
        // 尝试解析SSE数据
        const lines = chunkStr.split('\n');
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try {
              const jsonData = JSON.parse(line.substring(6));
              console.log(`📄 解析的SSE数据:`, JSON.stringify(jsonData, null, 2));
            } catch (e) {
              console.log(`❌ 解析SSE数据失败:`, e.message);
            }
          }
        }
        
        data += chunkStr;
      });
      
      res.on('end', () => {
        console.log(`✅ 流式响应完成，共收到${chunkCount}个chunk`);
        console.log(`📄 完整响应数据:`, data);
        resolve({ statusCode: res.statusCode, data, chunkCount });
      });
      
      res.on('error', (error) => {
        console.log(`❌ 响应流错误:`, error.message);
        reject(error);
      });
    });

    req.on('error', (error) => {
      console.log(`❌ 请求错误:`, error.message);
      reject(error);
    });

    req.on('timeout', () => {
      console.log(`⏰ 请求超时`);
      req.destroy();
      reject(new Error('Request timeout'));
    });

    req.setTimeout(30000); // 30秒超时
    req.write(postData);
    req.end();
  });
}

// 测试工具调用 - 使用非流式接口
function testToolCallNonStream() {
  return new Promise((resolve, reject) => {
    console.log('🔧 测试工具调用 - 非流式接口...');
    
    const postData = JSON.stringify({
      messages: [{ role: 'user', content: '查询所有任务' }],
      userId: '00287cfd-f5e2-403e-b78f-b9c327769986'
    });

    const options = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/chat-langchain/chat',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const req = http.request(options, (res) => {
      console.log(`📡 响应状态: ${res.statusCode}`);
      console.log(`📋 响应头:`, res.headers);
      
      let data = '';
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          console.log(`✅ 非流式响应成功:`, JSON.stringify(result, null, 2));
          resolve(result);
        } catch (error) {
          console.log(`❌ 解析响应失败:`, error.message);
          console.log(`📄 原始响应:`, data);
          reject(error);
        }
      });
    });

    req.on('error', (error) => {
      console.log(`❌ 请求错误:`, error.message);
      reject(error);
    });

    req.on('timeout', () => {
      console.log(`⏰ 请求超时`);
      req.destroy();
      reject(new Error('Request timeout'));
    });

    req.setTimeout(30000); // 30秒超时
    req.write(postData);
    req.end();
  });
}

// 运行测试
async function runTests() {
  console.log('🚀 开始详细测试工具调用问题...\n');
  
  try {
    console.log('='.repeat(50));
    console.log('测试1: 非流式接口');
    console.log('='.repeat(50));
    await testToolCallNonStream();
    
    console.log('\n' + '='.repeat(50));
    console.log('测试2: 流式接口');
    console.log('='.repeat(50));
    await testToolCallStream();
    
    console.log('\n✨ 所有测试完成！');
  } catch (error) {
    console.log('\n❌ 测试失败:', error.message);
  }
}

runTests();
